package com.jack006.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.jack006.utils.extend.AliyunResource;
import org.springframework.stereotype.Component;

/**
 * @Classname SMSUtils
 * @Description 短信发送类
 * @Date 2021-06-13 09:24
 * @Created by jack
 */
@Component
public class SMSUtils {

    private final AliyunResource aliyunResource;

    public SMSUtils(AliyunResource aliyunResource) {
        this.aliyunResource = aliyunResource;
    }

    public void sendSMS(String mobile, String code) {
        String result;
        try {
            Client client = createClient(aliyunResource.getAccessKeyId(), aliyunResource.getAccessKeySecret());
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName("600客街")
                    .setTemplateCode("每日新闻")
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            result = sendSmsResponse.toString();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    private Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

}
